import React from 'react';
import {connect} from 'dva/index';
import {Card, Col, DatePicker, Form, Popconfirm, Row, Statistic, Table, Tabs} from 'antd';
import styles from '../../../index.less';
import FormBase from '../../../../components/Base/FormBase';
import ViewTitle from "../../../../components/ViewTitle";
import {FormField, ModalView, SearchForm} from "antd-extra";
import Button from "antd/es/button";
import {exportExcel} from "../../../../utils/excelUtils";
import ModalCreateOrEditPaymentRecord from "../../modal/ModalCreateOrEditPaymentRecord";

import ModalPaymentRecordDetail from "../../modal/ModalPaymentRecordDetail";
import PaymentDataFaceAcceptance from "./PaymentDataFaceAcceptance";

const _ = require('lodash');

const table = 'Payment';
const {RangePicker} = DatePicker;
@Form.create()
@connect(({
            tenant,
            global,
            procure,
            dic, finance
          }) => ({...tenant, ...global, ...dic, ...procure, ...finance}))
export default class PaymentDataFaceAuxMaterial extends FormBase {
  constructor(props) {
    super(props);
    const {treeNode, title} = props;
    const {treeId} = treeNode;
    this.state = {treeId, title};
  }

  componentDidMount() {
    // const {treeId, title} = this.props;
    // this.state = {treeId, title};

    this.props.dispatch({
      type: 'vendor/findMany',
      payload: {}
    });
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
    this.props.dispatch && this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });

    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    const {treeNode} = this.props;
    const {treeId} = treeNode;
    payload.table = table;
    payload.treeId = treeId;

    this.props.dispatch({
      type: 'finance/findRecordMany',
      payload: {...payload}
    });
    this.props.dispatch({
      type: 'finance/findRecordStatistics',
      payload: {...payload}
    });
    this.props.dispatch({
      type: 'procure/findMany',
      payload: {}
    });
  }


  onDelete = record => {
    record.table = table;
    this.props.dispatch({
      type: 'finance/deleteRecord',
      payload: record
    }).then(res => {
      this.requestReturn(res);
      this.componentDidMount();
    });
  };

  onCreateOrEdit = async values => {
    const type = values ? "finance/updateRecord" : "finance/createRecord";
    const {treeNode, isProcure} = this.props;
    const oldAmount = values ? values.paymentAmount : 0;
    console.log('oldAmount', oldAmount);
    ModalView.open(ModalCreateOrEditPaymentRecord,
      {
        title: values ? '编辑记录' : "创建记录",
        width: '1080px'
      }, {
        values, table, isProcure, treeNode,
        callback: (payload) => {
          payload.table = table;
          payload.code = values ? values.code : 'FIN' + new Date().valueOf();
          const {treeId, name, mark = ""} = treeNode;
          payload.treeId = treeId;
          payload.treeName = name;
          payload.treeMark = mark;
          if (values) {
            payload.oldAmount = oldAmount;
          }
          console.log('payloadpayload', payload);
          this.props.dispatch({
            type,
            payload
          }).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        }
      });
  };

  getSearchFields = () => {
    const model = this.props[`${table}Model`];
    if (!model) return [];
    const arr = [];
    this.getSearchField(arr, model, "");
    arr.push(
      <FormField
        label="创建时间"
        name="createdTs"
        key={3}
        initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
      >
        <RangePicker allowClear={true}
          // style={{ width: '150%' }}
        />
      </FormField>
    );
    return arr;
  };

  exportExcel = async () => {
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    this.props.dispatch({
      type: 'finance/exportExcel',
      payload: {table, ...payload}
    }).then(res => {
      if (res) {
        const {result = {}} = res;
        const {header, data} = result;
        exportExcel(header, data, '收支记录');
      }
    });
  };

  tableCols() {
    const model = this.props[`${table}Model`];
    const cols = this.getTableColumns(model);
    cols.push(
      {
        title: '操作', dataIndex: 'opt', fixed: 'right', render: (text, record) => {
          return <div>
            <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '详情'}
               onClick={() => {
                 ModalView.open(ModalPaymentRecordDetail,
                   {
                     title: "付款记录详情",
                     width: '1080px'
                   }, {
                     values: record,
                     model: model,

                     callback: () => this.componentDidMount()
                   });
               }}>详情</a>
            <a style={{marginRight: '6px'}} disabled={record.reviewStatus === '同意'}
               onClick={() => this.onCreateOrEdit(record)}>编辑</a>
            {<Popconfirm
              title="确认删除"
              onConfirm={() => this.onDelete(record)}
              okText="是"
              cancelText="否"

            >
              <a disabled={record.reviewStatus === '同意'}>删除</a>
            </Popconfirm>}
          </div>;

        }
      }
    );
    return cols;
  }

  render() {
    const {
      _notify,
      form,
      PaymentRecords = [],
      statistics = {},
      isPayReview = false,
      treeNode = {},
      orders
    } = this.props;

    const {treeId} = treeNode;
    if (treeId !== this.state.treeId) {
      this.state.treeId = treeId;
      this.componentDidMount();
    }
    const {name} = treeNode;
    const {payment = 0} = statistics;

    return (
      <Form>
        <Tabs defaultActiveKey="1">
          <Tabs.TabPane tab={'付款记录'} key={1}>
            <ViewTitle title={name}
                       actions={[<Button
                         onClick={() => this.exportExcel()}
                       >导出</Button>,
                         !isPayReview && <Button type="primary"
                                                 onClick={() => this.onCreateOrEdit()}
                         >添加</Button>
                       ]}
            ></ViewTitle>
            <SearchForm
              style={{marginLeft: '6px', marginRight: '6px'}}
              onSearch={() => {
                this.state.current = 1;
                this.componentDidMount();
              }}
              onReset={this.handleReset}
              cols={3}
              min={10}
              expandText="展开"
              form={form}
            >
              {this.getSearchFields()}
            </SearchForm>
            <div style={{background: '#ECECEC', padding: '30px'}}>
              <Row gutter={16}>
                <Col span={12}>
                  <Card>
                    <Statistic
                      title={`总${name}统计`}
                      value={payment}
                      precision={2}
                      valueStyle={{color: '#13f'}}
                      suffix="元"
                    />
                  </Card>
                </Col>
              </Row>
            </div>
            <Table
              className={styles.antTable}
              bordered={true}
              // columns={this.getDicTableCols(model, this.onCreateOrEdit, this.onDelete)}
              columns={this.tableCols()}
              dataSource={PaymentRecords}
              scroll={{x: true}}
              pagination={true}
              defaultCurrent={1}
              total={500}
              showSizeChanger
              onShowSizeChange={(current, pageSize) => {
                console.log(current, pageSize);
              }}
            ></Table>
          </Tabs.TabPane>
          <Tabs.TabPane tab={'辅材采购验收统计'} key={2}>
            <PaymentDataFaceAcceptance materialType={"辅材"}></PaymentDataFaceAcceptance>
          </Tabs.TabPane>
        </Tabs>

      </Form>
    );
  }
}
